import { db } from "@/storage";
import { settingConfig } from "@/config";

/*
 *   加载指定文件
 *   使用 require.context()
 *   sort 进行路由排序
 */

export const loadRoutes = (files) =>
    files
        .keys()
        .reduce((arr, key) => {
            if (typeof files(key).default === "object")
                return arr.concat(files(key).default || files(key));
            return arr;
        }, [])
        .sort((prev, next) => (prev.meta?.sort || 0) - (next.meta?.sort || 0));

export const checkAuth = (key) => {
    const userPermissionMap = db.getMap("userPermissionMap");
    return true;
    // return !!userPermissionMap && !!userPermissionMap.get(key);
};

// 处理tree权限丢失父级id
// # 新增用户时给角色权限， 处理缺失id
// # origin： 权限数组  arr： 选中的权限id数组
export function setPermissionIds(origin = [], arr = []) {
    const _arr = [];
    function delIds(array) {
        array.forEach((item) => {
            if (!item.children && arr.includes(item.id)) {
                _arr.push(item.id);
            }
            if (item.children) {
                delIds(item.children);
            }
        });
    }
    delIds(origin);
    return _arr;
}

// # 角色回显数据时，去除丢失的id
// # origin： 权限原数组  arr： 选中的权限id数组
export function getPermissionIds(origin = [], arr = []) {
    const _ids = {};
    arr.forEach((id) => (_ids[id] = true));
    function setId(item) {
        if (_ids[item.id]) {
            return true;
        }
        let flag = false;
        if (Array.isArray(item.children)) {
            for (const child of item.children) {
                if (setId(child)) {
                    _ids[item.id] = true;
                    flag = true;
                }
            }
        }
        return flag;
    }
    origin.forEach((item) => setId(item));
    return Object.keys(_ids);
}

export function getVal(form, s) {
    return s
        .replace(/\[(\w+)\]/g, ".$1")
        .replace(/^\./, "")
        .split(".")
        .reduce((prev, cur) => prev && prev[cur], form);
}

export function getTokenByUrl(url) {
    const strs = url.split("?")[1];
    const paramt = strs.split("&");
    const obj = {};
    for (let i = 0; i < paramt.length; i++) {
        const g = paramt[i].split("=");
        obj[g[0]] = g[1];
    }
    return obj;
}

// 文件流下载

const { ipcRenderer } = window.require ? window.require("electron") : {}; // 兼容web和electron

export function download(value) {
    let blob = new Blob([value], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    let blobUrl = window.URL.createObjectURL(blob);
    let link = document.createElement("a");
    link.style.display = "none";
    link.download = "处分情况抓取分析.xlsx";
    link.href = blobUrl;
    if (window.require) {
        ipcRenderer.send("download", {
            downloadPath: link.href, // 下载链接（以下载vue文件为例）
            fileName: link.download, // 下载文件名，需要包含后缀名
        });
    } else {
        link.click();
    }
}

export const goKanban = (router) => {
    router.push({
        name: settingConfig.kanBanName,
    });
};

export const back = (router) => {
    router.back();
};

export function formateTimeStamp(time) {
    let date = new Date(time);
    let year = date.getFullYear();
    let month =
        date.getMonth() + 1 < 10
            ? "0" + (date.getMonth() + 1)
            : date.getMonth() + 1;
    let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();

    return year + "/" + month + "/" + day;
}

export function getNowTime(id) {
    let time = new Date();
    //获取时分秒
    let h = time.getHours();
    let m = time.getMinutes();
    let s = time.getSeconds();

    //检查是否小于10
    h = check(h);
    m = check(m);
    s = check(s);
    // document.getElementById('nowtime').innerHTML = h + ':' + m + ':' + s;
    const eleMent = document.getElementById(id);
    if (eleMent) {
        eleMent.innerHTML = h + ":" + m + ":" + s;
    }
}

export function check(i) {
    // 方法二，if语句判断
    if (i < 10) {
        i = "0" + i;
    }
    return i;
}
